package zaplogger

/**
* Author: joker
* TODO: test
* Date: 2022/8/18
* Time: 下午1:44
**/

import (
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"log"
	"mall-portalv2/conf"
	"mall-portalv2/library/common"
	"mall-portalv2/library/zaprotatelogs"
	"os"
	"time"
)

var (
	level zapcore.Level
)

type ZapConfig struct {
	Level         string `mapstructure:"level" json:"level" yaml:"level"`
	Format        string `mapstructure:"format" json:"format" yaml:"format"`
	AppName       string `mapstructure:"app_name" json:"app_name" yaml:"app_name"`
	AppVersion    string `mapstructure:"app_version" json:"app_version" yaml:"app_version"`
	Director      string `mapstructure:"director" json:"director"  yaml:"director"`
	LinkName      string `mapstructure:"link-name" json:"linkName" yaml:"link-name"`
	EncodeLevel   string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"`
	StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"`
	LogInConsole  bool   `mapstructure:"log-in-console" json:"logInConsole" yaml:"log-in-console"`
}

func NewZap(config *ZapConfig) (logger *zap.Logger) {

	if !common.Exists(conf.Config.Zap.Director) { // 判断是否有Director文件夹
		log.Printf("create logs directory\n")
		_ = os.Mkdir(conf.Config.Zap.Director, os.ModePerm)
	}

	level = checkZapLogLevel(config.Level)

	// 开启开发模式
	caller := zap.AddCaller()
	// 开启文件及行号
	development := zap.Development()
	//堆栈跟踪
	stacktrace := zap.AddStacktrace(checkZapLogLevel(config.Level))
	// 设置初始化字段
	fileds := zap.Fields(zap.String("app_name", config.AppName), zap.String("app_version", config.AppVersion))

	if level == zap.DebugLevel || level == zap.ErrorLevel {
		logger = zap.New(getEncoderCore(), caller, fileds, development, stacktrace)
	} else {
		logger = zap.New(getEncoderCore(), fileds)
	}

	defer logger.Sync()

	return logger
}

func checkZapLogLevel(intoLevel string) (level zapcore.Level) {
	// 初始化配置文件的Level
	switch intoLevel {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "ctx":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}
	return level
}

// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig() (config zapcore.EncoderConfig) {
	config = zapcore.EncoderConfig{
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "zaplogger",
		CallerKey:      "caller",
		StacktraceKey:  conf.Config.Zap.StacktraceKey,
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     CustomTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
	}
	switch {
	case conf.Config.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
		config.EncodeLevel = zapcore.LowercaseLevelEncoder
	case conf.Config.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
		config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case conf.Config.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
		config.EncodeLevel = zapcore.CapitalLevelEncoder
	case conf.Config.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
		config.EncodeLevel = zapcore.CapitalColorLevelEncoder
	default:
		config.EncodeLevel = zapcore.LowercaseLevelEncoder
	}
	return config
}

// getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
	if conf.Config.Zap.Format == "json" {
		return zapcore.NewJSONEncoder(getEncoderConfig())
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig())
}

// getEncoderCore 获取Encoder的zapcore.Core
func getEncoderCore() (core zapcore.Core) {
	writer, err := zaprotatelogs.GetWriteSyncer(conf.Config.Zap.Director, conf.Config.Zap.LinkName, conf.Config.Zap.LogInConsole) // 使用file-rotatelogs进行日志分割
	if err != nil {
		fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
		return
	}
	return zapcore.NewCore(getEncoder(), writer, level)
}

// 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format("2006/01/02-15:04:05.000"))
}
